package com.idiot.service.impl;

import com.github.pagehelper.Page;
import com.idiot.domain.common.exceptions.MyException;
import com.idiot.domain.common.utils.EncodeMD5;
import com.idiot.domain.common.utils.IdGen;
import com.idiot.domain.dao.IUserDao;
import com.idiot.domain.dao.IUserRoleDao;
import com.idiot.domain.model.User;
import com.idiot.domain.model.UserRole;
import com.idiot.service.IUserService;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;


/**
 * Created by idiot on 2016/12/13.
 */
@Service
public class UserServiceImpl implements IUserService {
    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private IUserDao userDao;
    @Resource
    private IUserRoleDao userRoleDao;


    @Override
    public User getUserByName(String userName) {
        return userDao.getUserByName(userName);
    }

    @Override
    public Page<User> getAllAdminUsers(RowBounds rowBounds) {
        return userDao.getAllAdminUsers(rowBounds);
    }

    @Override
    public void insert(User info) {
        info.setUserId(IdGen.get().nextId());   //设置userId
        info.setUserPassword(EncodeMD5.GetMD5Code(info.getUserPassword())); //加密密码
        if(userDao.insert(info) < 1){
            throw new MyException("新增用户失败");
        }
    }

    @Override
    public void update(User info) {
        if(userDao.update(info) < 1){
            throw new MyException("修改用户失败");
        }
    }

    @Override
    public User getUserByUserId(long userId) {
        return userDao.getUserByUserId(userId);
}

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(long userId) {
        //删除用户信息  成功之后继续删除用户角色信息
        if(userDao.delete(userId) < 1){
            logger.error("删除用户信息失败");
        }
        //根据userId查询该用户拥有的角色
        List<UserRole> list = userRoleDao.getUserRolesByUserId(userId);
        if(list != null && list.size() > 0){
            if(userRoleDao.deleteUserRolesByUserId(userId) < 1){
                logger.error("删除用户角色关系信息失败");
            }
        }
    }

    @Override
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }
}
